import { EventDispatcher, Event } from "../events";

var init_time = Date.now();

/**
 * 程序到现在运行时间ms
 */
export function getTimer() {
  return Date.now() - init_time;
}

export class Timer extends EventDispatcher<"timer" | "timer_complete"> {
  private currentCount = 0;
  private running = false;
  private t!: NodeJS.Timeout;
  constructor(public delay: number, public repeatCount = 0) {
    
  super();}
  start() {
    if (this.running) {
      return;
    }
    this.running = true;
    this.t = setTimeout(() => {
      this.currentCount++;
      this.dispatchEvent(new Event("timer"));
      this.dispatchEvent(new Event("timer_complete"));
      if (this.repeatCount === 0 || this.currentCount < this.repeatCount) {
        this.running = false;
        this.start();
      }
    }, this.delay);
  }
  stop() {
    if (this.running) {
      clearTimeout(this.t);
    }
    this.running = false;
  }
  reset() {
    this.stop();
    this.currentCount = 0;
  }
}
